﻿using KPIS.GERP.Models;
using KPIS.GERP.Models.Class;
using System;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.BGM;
using OfficeOpenXml.Table;
using Resources;
using System.Collections.Generic;
using System.Data;
using KPIS.GERP.WEB.GIMS.Class;
using System.Web;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class PrePurchaseController : Controller
    {
        public static string[] _basicIncludeSubclass = new[]
        {
            "Priority", "DurationType", "DurationCount", "YearType", "RequestJobSite", "MasPurchaseType"
            //"Committees", "Files", "PrePurchaseRequestItems" , "RequestEmployee", "Progress"
        };

        public ActionResult Index(int? filterJobSiteId = null, bool ContentOnlyReset = false)
        {
            if (ContentOnlyReset)
            {
                GimsUtilities.ContentOnly = false;
            }
            var service = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
            var models = service.Select(new PrePurchaseRequest {RecordStatus = "!D"}, _basicIncludeSubclass);
            ViewBag.FilterJobSiteId = filterJobSiteId;

            return View(models);
        }

        public ActionResult _EditorForm(int id)
        {
            return Details(id, true);
        }

        public ActionResult Details(int id, bool nolayout = false, bool ContentOnlyReset = false)
        {
            if (ContentOnlyReset)
            {
                GimsUtilities.ContentOnly = false;
            }
            var service = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
            service.CreateCommitteeGroupIfNotExist(id);
            var model = service.Select(new PrePurchaseRequest {PprId = id}, _basicIncludeSubclass).FirstOrDefault();
            ViewBag.EmptyLayout = nolayout;
            return View(model);
        }

        public ActionResult Create()
        {
            var selectedList =
                new KPIS.GERP.WEB.GIMS.JobsiteService.JobsiteServiceClient().LoadInternalJobSiteSelectList(
                    GimsMembership.User.Employee.WorkingJobSiteId, true, 3).FirstOrDefault(o => o.Selected == true);
            var selectedJobSiteId = selectedList != null ? (int?) Convert.ToInt32(selectedList.Value) : null;
            var jobsiteId = selectedJobSiteId ?? GimsMembership.User.Employee.WorkingJobSiteId;
            var serviceBgmSystemControl = new BgmSystemControlService.BgmSystemControlServiceClient();
            var model = new PrePurchaseRequest
            {
                RequestEmpId = Class.GimsMembership.CurrentEmpId,
                YearTypeId = 1,
                BgYear = serviceBgmSystemControl.BgYear(),
                RequestDate = DateTime.Today,
                PriorityId = 6,
                PcTypeId = 1,
                RequestJobSiteId = jobsiteId.HasValue ? jobsiteId.Value : 0,
                DurTypeId = 10,
                RequireDuration = 15
            };

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(PrePurchaseRequest model, FormCollection collection, bool EmptyLayout = false)
        {
            ViewBag.EmptyLayout = EmptyLayout;
            model = VarifyModel(model, collection);
            if (ModelState.IsValid)
            {
                var service = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
                model.ProgressId = 22; // MasLookUp --> PrePurchaseRequest

                var serviceGroup = new CommitteeGroupService.CommitteeGroupServiceClient();
                int committeeGroupId = serviceGroup.Insert(new CommitteeGroup(), Class.GimsMembership.CurrentEmpId);

                model.CommitteeGroupId = committeeGroupId;

                var id = service.Insert(model, Class.GimsMembership.CurrentEmpId);

                var committeeGroup = serviceGroup.Select(new CommitteeGroup
                {
                    CommitteeGroupId = committeeGroupId
                }, null).First();

                committeeGroup.CreateByPprId = id;
                serviceGroup.Update(committeeGroup, GimsMembership.CurrentEmpId);

                return RedirectToAction("Details", new {id, EmptyLayout});
            }

            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var service = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
            var model = service.Select(new PrePurchaseRequest {PprId = id}, _basicIncludeSubclass).FirstOrDefault();

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int id, PrePurchaseRequest model, FormCollection collection, bool emptyLayout = false)
        {
            model = VarifyModel(model, collection);
            if (ModelState.IsValid)
            {
                var service = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
                service.Update(model, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Details", new {id, emptyLayout});
            }
            return View(model);
        }

        public ActionResult Delete(int id)
        {
            var service = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
            service.Delete(id, Class.GimsMembership.CurrentEmpId);
            service.Close();

            return RedirectToAction("Index");
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            if (deleteIds == null)
                return Json(new {success = true});

            try
            {
                var service = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
                foreach (int delete in deleteIds)
                {
                    service.Delete(delete, Class.GimsMembership.CurrentEmpId);
                }

                ModelState.AddModelError(ErrorLocalization.Error,
                    string.Format("ลบข้อมูลไปทั้งหมด {0} รายการ", deleteIds.Length.ToString("#,##0")));
                return Json(new {success = true});
            }
            catch (Exception ex)
            {
                Models.Class.GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return Json(new {success = false});
            }
        }

        private PrePurchaseRequest VarifyModel(PrePurchaseRequest model, FormCollection collection)
        {
            if (!model.DurTypeId.HasValue)
            {
                ModelState.AddModelError("DurTypeId", "กรุณาเลือกวันที่ต้องการใช้งาน");
            }

            if (model.DurTypeId == 10 && !model.RequireDuration.HasValue)
            {
                ModelState.AddModelError("RequireDuration", "กรุณากรอกจำนวนวันที่ต้องการใช้งาน");
            }

            // Resolve Request Date as NaN\NaN\NaN
            var dt = collection["RequestDate2"];
            DateTime dtv;
            DateTime.TryParse(dt, out dtv);
            model.RequestDate = dtv == DateTime.MinValue ? DateTime.Now : dtv;

            return model;
        }

        public void ReportPrePurchase(Int32 PprId)
        {
            MailMerge mailMerge = new MailMerge();

            var servicePrePurchaseRequest = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();
            var servicePrePurchaseRequestItem = new PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
            var committeeService = new CommitteeService.CommitteeServiceClient();
            var userService = new UserService.UserServiceClient();
            var jobsiteService = new JobsiteService.JobsiteServiceClient();
            var projectService = new ProjectOperationService.ProjectOperationServiceClient();

            var ModelPrePurchaseRequest =
                servicePrePurchaseRequest.Select(new PrePurchaseRequest {PprId = PprId}, _basicIncludeSubclass)
                    .FirstOrDefault();
            var ModelPrePurchaseRequestItem =
                servicePrePurchaseRequestItem.Select(new PrePurchaseRequestItem {PprId = ModelPrePurchaseRequest.PprId}
                    , new[] { 
                        "PrePurchaseRequest", 
                        "MasResourceItem.MasUnit", 
                        "ProjectOperationExpense.ProjectOperation", 
                        "ProjectOperationExpense.ProjectExpense.Project"
                    })
                    .ToList();

            var ModelUser = userService.GetUsers().FirstOrDefault(o => o.EmpId == ModelPrePurchaseRequest.CreatedBy);
            var ModelJobsite = jobsiteService.SelectNameJobSite(ModelPrePurchaseRequest.RequestJobSiteId);

            Dictionary<string, string> fields = new Dictionary<string, string>();
            fields.Add("D2", ModelPrePurchaseRequest.Code.ToString());
            string strDate = ModelPrePurchaseRequest.CreatedWhen.ToString();
            string strRequestDate = ModelPrePurchaseRequest.RequireDate.ToString();


            if (ModelPrePurchaseRequestItem.Count != 0)
            {
                int ProjId =
                    ModelPrePurchaseRequestItem.FirstOrDefault().ProjectOperationExpense.ProjectExpense.Project.ProjId;
                Decimal TotalAmount =
                    /* projectService.SelectProjectExpense(new ProjectExpense {ProjId = ProjId}, null)
                        .ToList()
                        .Sum(m => m.TotalAmount) ?? 0;*/
                    ModelPrePurchaseRequestItem.Sum(o => o.Amount) ?? 0;
                string StrBgmName =
                    ModelPrePurchaseRequestItem.FirstOrDefault().ProjectOperationExpense.ProjectExpense.Project.Name;
                string[] StrC = StrBgmName.Split(')');
                string BgmName = StrC[0];
                string BgmNo = StrC.Count() > 1 ? StrC[1] : "";
                fields.Add("C6", "เบิกจากแผนงาน " + BgmName + ")");
                fields.Add("C7", "รหัสกิจกรรม " + BgmName + ") /" + BgmNo);
                fields.Add("C9", TotalAmount.ToString("#,##0.00"));
            }
            else
            {
                fields.Add("C6", " ");
                fields.Add("C7", " ");
                fields.Add("C9", " ");
            }


            string[] strA = strRequestDate.Split(' ');
            string[] strB = strDate.Split(' ');
            string RequestDate = strA[0];
            string CreatedWhen = strB[0];
            fields.Add("C3", ModelUser.FullName);
            fields.Add("C4", ModelPrePurchaseRequest.Name);

            var jobsiteName = ModelUser.Employee != null && ModelUser.Employee.JobSite != null
                ? ModelUser.Employee.JobSite.Name
                : "(ไม่มีข้อมูลหน่วยงาน)";
            var positionName = ModelUser.Employee != null && ModelUser.Employee.Position != null &&
                               ModelUser.Employee.Position.Name != null
                ? ModelUser.Employee.Position.Name
                : "";
            fields.Add("E3", jobsiteName);
            fields.Add("F2", CreatedWhen.ToString());
            // fields.Add("C8", RequestDate.ToString());
            fields.Add("C8", RequireDate(ModelPrePurchaseRequest));
            fields.Add("C5", ModelPrePurchaseRequest.Reason);

            int addItemMoreRow = 0;
            if (ModelPrePurchaseRequestItem != null)
            {
                for (int i = 0; i < ModelPrePurchaseRequestItem.Count; i++)
                {
                    int n = i + 11;
                    int Count = i + 1;
                    fields.Add("A" + n.ToString(), Count.ToString());
                    fields.Add("B" + n.ToString(),

                        (ModelPrePurchaseRequestItem[i].ProjectOperationExpense != null &&
                         ModelPrePurchaseRequestItem[i].ProjectOperationExpense.ProjectOperation != null
                            ? ModelPrePurchaseRequestItem[i].ProjectOperationExpense.ProjectOperation.Code + " - "
                            : "") +

                        (ModelPrePurchaseRequestItem[i].ResItemId != null
                            ? /*ระบุ ใช้ชื่อ Item */ ModelPrePurchaseRequestItem[i].MasResourceItem.Name
                            : /*ไม่ระบุ ใช้รายละเอียด*/ ModelPrePurchaseRequestItem[i].Descr)

                        );
                    fields.Add("C" + n.ToString(),
                        ModelPrePurchaseRequestItem[i].MasResourceItem == null
                            ? " "
                            : ModelPrePurchaseRequestItem[i].MasResourceItem.MasUnit.Name);
                    fields.Add("D" + n.ToString(), (ModelPrePurchaseRequestItem[i].Qty ?? 0).ToString("#,##0"));
                    fields.Add("E" + n.ToString(), (ModelPrePurchaseRequestItem[i].Price ?? 0).ToString("#,##0.00"));
                    fields.Add("F" + n.ToString(), (ModelPrePurchaseRequestItem[i].Amount ?? 0).ToString("#,##0.00"));
                    if (n >= 15) addItemMoreRow++;
                }
            }
            else
            {
                fields.Add("A11", " ");
                fields.Add("B11", " ");
                fields.Add("C11", " ");
                fields.Add("D11", " ");
                fields.Add("E11", " ");
                fields.Add("F11", " ");
            }

            if (ModelPrePurchaseRequest.CommitteeGroupId == null)
            {
                fields.Add("D" + (18 + addItemMoreRow), " ");
            }
            else
            {

                var ModelCommittee =
                    committeeService.Select(
                        new Committee {CommitteeGroupId = ModelPrePurchaseRequest.CommitteeGroupId, RecordStatus = "!D"},
                        null).ToList();
                int templateCommitteeRow = 3;
                int addItemMoreRowTemp = addItemMoreRow;
                //64	7	คณะกรรมการจัดซื้อ/จ้างโดยวิธีพิเศษ
                //65	7	คณะกรรมการตรวจรับพัสดุ/งานจ้าง
                //66	7	เจ้าหน้าที่ตรวจรับ
                //76	7	คณะกรรมการตรวจนับ
                var committe64 = ModelCommittee.Where(o => o.ComFunctionId == 64).ToArray();
                var committe6566 = ModelCommittee.Where(o => o.ComFunctionId == 65 || o.ComFunctionId == 66 || o.ComFunctionId == 76).ToArray();
                for (int i = 0; i < committe64.Count(); i++)
                {
                    int n = i + (18 + addItemMoreRowTemp);
                    int Count = i + 1;
                    fields.Add("A" + n, Count + ".  " + committe64[i].EmpName); 
                }
                for (int i = 0; i < committe6566.Count(); i++)
                {
                    int n = i + (18 + addItemMoreRowTemp);
                    int Count = i + 1;
                    fields.Add("D" + n, Count + ".  " + committe6566[i].EmpName);
                }
            }

            if (ModelPrePurchaseRequestItem != null)
            {
                decimal SumAmount = Convert.ToDecimal(ModelPrePurchaseRequestItem.ToList().Sum(m => m.Amount));
                decimal dVat = SumAmount*7/100;
                decimal dIncludeVat = SumAmount + dVat;

                try
                {
                    fields.Add("F" + (15 + addItemMoreRow), SumAmount.ToString("#,##0.00"));
                }
                catch
                {
                }
                //Comment out on 9/4/57 ไม่ต้องการให้แสดงภาษี และยอดรวม
                //fields.Add("F16", dVat.ToString("#,##0.00"));
                //fields.Add("F17", dIncludeVat.ToString("#,##0.00"));

            }
            else
            {
                fields.Add("F" + (15 + addItemMoreRow), " ");
                fields.Add("F" + (16 + addItemMoreRow), " ");
                fields.Add("F" + (17 + addItemMoreRow), " ");
            }
            fields.Add("A" + (29 + addItemMoreRow), "( " + ModelUser.FullName + " )");
            fields.Add("D" + (29 + addItemMoreRow), "(                                   )");
            fields.Add("A" + (30 + addItemMoreRow), positionName);
            fields.Add("A" + (28 + addItemMoreRow), "(ลงชื่อ)                                          ผู้ขอซื้อ/จ้าง");
            fields.Add("D" + (28 + addItemMoreRow),
                "(ลงชื่อ)                                                 ผู้อนุมัติ");

            string fileName = string.Format("รายงานแจ้งความประสงค์-{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
            string fileNameUtf8 = HttpUtility.UrlEncode(string.Format(fileName, System.Text.Encoding.UTF8));
            mailMerge.MergeExcel(Response, Server.MapPath("~/Templates/รายงานแจ้งความประสงค์.xlsx"),
                fileNameUtf8, null, fields, TableStyles.None, 14, addItemMoreRow);
        }

        private string RequireDate(PrePurchaseRequest Model)
        {
            string result = "";
            var emps = new KPIS.GERP.WEB.GIMS.EmployeeService.EmployeeServiceClient().Select(null, null, false);
            var LookUpService = new KPIS.GERP.WEB.GIMS.IcmMasLookUpService.IcmMasLookUpServiceClient();
            var durCountSelectList =
                LookUpService.MasLookUpSelectList(KPIS.GERP.Models.ICM.IcmMasLookUpType.LookUpType.DurationCount);
            var durCountSelectListItem =
                durCountSelectList.FirstOrDefault(
                    o => o.Value == (Model != null ? Convert.ToString(Model.DurCountId) : ""));
            var durCountWording = durCountSelectListItem == null ? string.Empty : durCountSelectListItem.Text;
            if (Model.DurTypeId == 10)
            {
                var task = new GERPContext().Tasks.OrderByDescending(o => o.TaskId)
                    .FirstOrDefault(o => o.RefId == Model.PprId && o.AppPrcId == 6);

                result += Model.RequireDuration + " วัน นับจาก " + durCountWording;

                if (Model.DurCountId == 10) //วันที่สร้างรายการ
                {
                    if (Model.CreatedWhen.HasValue)
                    {
                        result += "(วันที่สร้างรายการ คือ " + @Model.CreatedWhen.Value.ToString("dd MMM yyyy") + ")";
                    }
                }
                else if (Model.DurCountId == 11) // วันที่ยืนยันรายการ - ส่งขออนุมัติรายการ
                {
                    if (task != null && task.CreatedWhen.HasValue)
                    {
                        result = "(วันที่ยืนยันรายการ คือ " + @task.CreatedWhen.Value.ToString("dd MMM yyyy") + ")";
                    }
                }
                else if (Model.DurCountId == 12) // วันที่อนุมัติรายการ
                {
                    if (task != null && task.ApprovedWhen.HasValue)
                    {
                        result = "(วันที่อนุมัติรายการ คือ " + @task.ApprovedWhen.Value.ToString("dd MMM yyyy") + ")";
                    }
                }
            }
            else
            {
                result = "วันที่ " + (Model.RequireDate != null ? Model.RequireDate.Value.ToString("dd MMM yyyy") : "");
            }
            return result;
        }
    }
}